package com.youmingxing.utils;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import com.youmingxing.bean.User;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

/**
 * Created by chihiro on 15/9/7.
 * Edited by ChenZhixi
 */
public class Util {


    public static String getSDCardCachePath(Context context) {
        String path;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// 有SD卡
            path = Environment.getExternalStorageDirectory().getPath() + "/Android/data/" + context.getPackageName()
                    + "/";
        } else {
            path = Environment.getDataDirectory().getPath() + "/data/" + context.getPackageName() + "/";
        }

        File file = new File(path);
        if (!file.isDirectory()) {
            file.mkdirs();
        }

        return path;
    }

    public static String getPath(Context context, Uri uri) {
        if ("content".equalsIgnoreCase(uri.getScheme())) {
            String[] projection = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;
            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow("_data");
                if (cursor.moveToFirst()) {
                    return cursor.getString(column_index);
                }
            } catch (Exception e) {

            } finally {
                if (cursor != null)
                    cursor.close();
            }
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }


    public static String generateInfo(String[] userData) {
        String info = "";
        String gender = userData[User.Info.gender.ordinal()];
        if (!gender.equals("未知")) {
            info = gender;
        }
        String age = userData[User.Info.birthday.ordinal()];
        if (!age.equals("")) {
            age = age.substring(0, 4);
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int birthday = StringUtil.stringToInt(age);
            int ageInt = year - birthday > 0 ? year - birthday : 0;
            age = ageInt + "岁";
            if (info.equals("")) {
                info = age;
            } else {
                info = info + " / " + age;
            }
        }
        String place = userData[User.Info.address.ordinal()];
        if (!place.equals("")) {
            if (place.contains(",")) {
                place = place.substring(0, place.indexOf(","));
            }
            if (info.equals("")) {
                info = place;
            } else {
                info = info + " / " + place;
            }
        }
        String schoolOrJob = userData[User.Info.career_or_college.ordinal()];
        if (!schoolOrJob.equals("")) {
            if (info.equals("")) {
                info = schoolOrJob;
            } else {
                info = info + " / " + schoolOrJob;
            }
        }
        return info;
    }

    public static byte[] Bitmap2Bytes(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }


    public static String saveImageToGallery(Context context, Bitmap bmp) {
//        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".png";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        bmp.recycle();
        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        try {
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile
                    (file)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file.getAbsolutePath();
    }

    //压缩bitmap
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {    //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
        return bitmap;
    }

}
